package com.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.library.entity.Book;
import com.library.mapper.BookMapper;
import com.library.service.BookService;
import com.library.vo.PageVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 书籍Service实现
 *
 * @author Library Team
 */
@Slf4j
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Override
    public PageVO<Book> getBookPage(Long current, Long size, String title, String author, String category) {
        Page<Book> page = new Page<>(current, size);
        IPage<Book> result = baseMapper.selectBookPage(page, title, author, category);

        PageVO<Book> vo = new PageVO<>();
        vo.setCurrent(result.getCurrent());
        vo.setSize(result.getSize());
        vo.setTotal(result.getTotal());
        vo.setPages(result.getPages());
        vo.setRecords(result.getRecords());

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addBook(Book book) {
        book.setAvailableQuantity(book.getTotalQuantity());
        boolean result = save(book);
        if (result) {
            log.info("添加书籍成功 - {}", book.getTitle());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBook(Book book) {
        // 查询原书籍信息
        Book oldBook = getById(book.getId());
        if (oldBook == null) {
            throw new RuntimeException("书籍不存在");
        }

        // 如果总库存发生变化，同步更新可借数量
        if (!oldBook.getTotalQuantity().equals(book.getTotalQuantity())) {
            Integer borrowedCount = oldBook.getTotalQuantity() - oldBook.getAvailableQuantity();
            book.setAvailableQuantity(book.getTotalQuantity() - borrowedCount);
        }

        // 设置更新时间，避免数据库约束违反
        book.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(book);
        if (result) {
            log.info("更新书籍成功 - {}", book.getTitle());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBook(Long id) {
        // 查询书籍信息
        Book book = getById(id);
        if (book == null) {
            throw new RuntimeException("书籍不存在");
        }

        // 手动设置逻辑删除标记和更新时间，避免数据库约束违反
        book.setDeleted(1);
        book.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(book);
        if (result) {
            log.info("删除书籍成功 - ID: {}", id);
        }
        return result;
    }

    @Override
    public Book getBookById(Long id) {
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAvailableQuantity(Long id, Integer quantity) {
        Book book = getById(id);
        if (book == null) {
            throw new RuntimeException("书籍不存在");
        }

        book.setAvailableQuantity(book.getAvailableQuantity() + quantity);

        if (book.getAvailableQuantity() < 0) {
            throw new RuntimeException("可借数量不足");
        }

        book.setUpdatedAt(LocalDateTime.now()); // 设置更新时间，避免数据库约束违反

        boolean result = updateById(book);
        if (result) {
            log.info("更新书籍可借数量成功 - ID: {}, 数量: {}", id, quantity);
        }
        return result;
    }

}
